import React, { Component, useContext, useState, useEffect, useRef } from 'react';
import { Table, Input, Form, Space, Button, InputNumber } from 'antd';
import TheAreaEditor from '@/components/TheArea/editor';
import '../style/index.less'

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  linkageSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const [addressData, setAddressData] = useState({});
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing && record.type === 'input') {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  const setAreaData = (areaData) => {
    setAddressData({
      addressProvinceId: areaData.province,
      addressCityId: areaData.city,
      addressDistrictId: areaData.area,
      addressProvince: areaData.provinceName,
      addressCity: areaData.cityName,
      addressDistrict: areaData.areaName,
    })
  }
  if (editable) {
    childNode = editing ? (
      record.type === 'input' ? <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[{ required: true, message: '值为必填' }]}
      >
        <Input ref={inputRef} onPressEnter={save} />
      </Form.Item> : record.type === 'inputNumber' ? <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[{ required: true, message: '值为必填' }]}
      >
        <InputNumber ref={inputRef} onPressEnter={save} />
      </Form.Item> : <Space>
        <TheAreaEditor setAreaData={setAreaData} addressData={record.addressData} />
        <Button type='primary' onClick={() => {
          linkageSave(addressData)
          setEditing(!editing);
        }}>确认</Button>
        <Button onClick={() => setEditing(!editing)}>取消</Button>
      </Space>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};

class OrderCon extends Component {
  formRef = React.createRef()
  inputRef = React.createRef()
  state = {
    loading: false,
    dataSource: [],
    columns: [
      {
        title: '配置项',
        dataIndex: "key",
        key: "key",
        align: 'center',
        width: '50%',
      },
      {
        title: '值',
        dataIndex: "value",
        key: "value",
        align: 'center',
        editable: true,
        render: (text, record) => {
          return <div>
            {record.value}
          </div>
        },
        width: '50%'
      },
    ],
    editIndex: null,
    editValue: ''
  }

  async componentDidMount() {
    await this.getData()
  }

  getData = async () => {
    React.$post('/management/salesReturnAddress/list').then(response => {
      if (response.code === 0) {
        let data = response.data
        let dataSource = [
          {
            key: '收件人',
            value: data.addresseeName,
            type: 'input',
            name: 'addresseeName'
          },
          {
            key: '联系方式',
            value: data.addresseeMobile,
            type: 'inputNumber',
            name: 'addresseeMobile'
          },
          {
            key: '地区',
            value: data.addressProvince + data.addressCity + data.addressDistrict,
            addressData: {
              province: data.addressProvinceId,
              city: data.addressCityId,
              area: data.addressDistrictId,
              provinceName: data.addressProvince,
              cityName: data.addressCity,
              areaName: data.addressDistrict
            },
            type: 'linkage'
          },
          {
            key: '详细地址',
            value: data.addressDetail,
            type: 'input',
            name: 'addressDetail'
          },
        ]
        let salesReturnAddressId = data.salesReturnAddressId
        this.setState({
          dataSource,
          salesReturnAddressId
        })
      }
    })
  }

  handleSave = async (row) => {
    React.$post('/management/salesReturnAddress/edit', { [row.name]: row.value, salesReturnAddressId: this.state.salesReturnAddressId }).then(res => {
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '修改成功'
        })
        this.getData()
      }
    })
  }
  linkageSave = async (row) => {
    React.$post('/management/salesReturnAddress/edit', { ...row, salesReturnAddressId: this.state.salesReturnAddressId }).then(res => {
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '修改成功'
        })
        this.getData()
      }
    })
  }
  render() {
    const { loading, dataSource } = this.state
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.state.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
          linkageSave: this.linkageSave
        }),
      };
    });
    return <div className={"p-layout-box configuration"}>
      <div className={'platform-set-list'}>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          loading={loading}
          pagination={false}
          {...this.props}
        />
      </div>
    </div>
  }
}

export default OrderCon
